package com.iwdnb.gkgz.common.utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.iwdnb.bmnf.common.service.CacheService;
import com.iwdnb.bmnf.common.utils.BeanConvertUtils;
import com.iwdnb.gkgz.common.model.dto.StockDayData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import static com.iwdnb.gkgz.common.constant.CacheConstants.REALTIME_DATA_CACHE_PREFIX;

@Component
@Slf4j
public class RealtimeStockUtils implements ApplicationContextAware {

    private static CacheService cacheService;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        cacheService = applicationContext.getBean(CacheService.class);
    }

    public static StockDayData getRealtimeData(String code) {
        return getRealtimeData(code, false);
    }

    public static StockDayData getRealtimeData(String code, boolean syncFlag) {
        String date = DateUtil.formatDate(new Date());
        String cacheKey = REALTIME_DATA_CACHE_PREFIX + date + ":" + code;
        StockDayData stockDayData = cacheService.get(cacheKey);
        if (!syncFlag && Objects.nonNull(stockDayData)) {
            return stockDayData;
        }
        syncRealtimeDatas(Lists.newArrayList(code));
        return cacheService.get(cacheKey);
    }

    public static List<StockDayData> syncRealtimeDatas(List<String> codes) {
        List<StockDayData> stockDayDataList = StockUtils.getRealtimeStockDataList(codes);
        for (StockDayData stockDayData : stockDayDataList) {
            String cacheKey = REALTIME_DATA_CACHE_PREFIX + stockDayData.getDate() + ":"
                + stockDayData.getCode();
            StockDayData old = cacheService.get(cacheKey);
            List<StockDayData> fenshiList = Objects.nonNull(old) && CollectionUtils.isNotEmpty(old.getFenshiList())
                ? old.getFenshiList() : new ArrayList<>();
            int second = DateUtil.parseDateTime(stockDayData.getDatetime()).getSeconds();
            if (second < 10) {
                fenshiList.add(BeanConvertUtils.convert(stockDayData, StockDayData.class));
            }
            stockDayData.setFenshiList(fenshiList);
            cacheService.put(cacheKey, stockDayData, 86400);
        }
        log.info("{}-{}-syncRealtimeDatas finished.", codes, DateUtil.formatDateTime(new Date()));
        return stockDayDataList;
    }
}
